package com.fragment;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import util.ApplicationConstant;

import com.activity.MainAppActivity;
import com.activity.R;

import dao.HttpPostThread;
import dao.LoadCategory;
import dao.LoadLocate;
import entities.Category;
import adapter.AdapterMainCategory;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

/*
 * LocateCategory dung lam webservice
 */
public class MainFragment extends Fragment {

	private MainAppActivity mainAppActivity;
	private ListView listViewCategory;
	private AdapterMainCategory adapterMainCategory;
	public static List<Category> listCategory = new ArrayList<Category>();
	public static LinearLayout layoutLoading;
	public static LinearLayout layoutConectionFailed;
	public boolean isConnectingToInternet() {
		ConnectivityManager connectivity = (ConnectivityManager) mainAppActivity
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null)
				for (int i = 0; i < info.length; i++)
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}

		}
		return false;
	}

	public boolean isGPSEnable() {
		LocationManager mlocManager = (LocationManager) mainAppActivity
				.getSystemService(Context.LOCATION_SERVICE);
		;
		return mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		this.mainAppActivity = (MainAppActivity) activity;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub

		Log.d("--thoainguyen category begin size:", "" + listCategory.size());
		MainAppActivity.TAG_FRAGMENT = "MainFragment";
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		View rootView = inflater.inflate(R.layout.main_app_fragment, container,
				false);
		// find view by id
		layoutLoading = (LinearLayout) rootView
				.findViewById(R.id.layout_main_loading);
		layoutConectionFailed = (LinearLayout) rootView
				.findViewById(R.id.layout_conection_failed);
		listViewCategory = (ListView) rootView
				.findViewById(R.id.listView_main_category);
		adapterMainCategory = new AdapterMainCategory(getActivity(),
				R.layout.main_menu_item, listCategory);
		listViewCategory.setAdapter(adapterMainCategory);
		listViewCategory.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				// TODO Auto-generated method stub
				LoadLocate.listLocate.clear();
				Category c = listCategory.get(pos);
				if (MainAppActivity.localeCode.equals("vi"))
					mainAppActivity.navigateToListLocate(c.getCategoryId(),
							c.getName());
				else
					mainAppActivity.navigateToListLocate(c.getCategoryId(),
							c.getEngName());
			}
		});
		// check GPS and internet
		if (isConnectingToInternet() == false) {
			Toast.makeText(mainAppActivity,
					"Coffeedy:conection is unavailabel", Toast.LENGTH_LONG)
					.show();
			Log.d("---thoainguyen mainappactivity", "conection is unavailabel");
			layoutConectionFailed.setVisibility(View.VISIBLE);
		} else {
			layoutConectionFailed.setVisibility(View.GONE);
			// run webservice
			if (listCategory.size() == 0) {
				dao.LoadCategory loadCategory = new dao.LoadCategory(handler);
				loadCategory.execute();
			}
			if (isGPSEnable() == false) {
				Toast.makeText(mainAppActivity, "GPS is off", Toast.LENGTH_LONG)
						.show();
				Log.d("---thoainguyen mainappactivity", "GPS is off");
			}
		}
		
		return rootView;
	}

	// load list category
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HttpPostThread.SUCCESS:
				String answer = (String) msg.obj;
				Log.d("--thoainguyen answer:", answer);
				if (answer != null) {
					try {
						JSONObject jsonObj = new JSONObject(answer);
						JSONArray jsonCaterories = jsonObj
								.getJSONArray(ApplicationConstant.JSON_ARRAY_CATEGORIES);
						for (int i = 0; i < jsonCaterories.length(); i++) {
							Log.d("---thoai nguyen", "getting json...");
							JSONObject jsonCategory = jsonCaterories
									.getJSONObject(i);
							final String id = jsonCategory
									.getString(ApplicationConstant.COL_CATEGORY_ID);
							String name = jsonCategory
									.getString(ApplicationConstant.COL_CATEGORY_NAME);
							String engName = jsonCategory
									.getString(ApplicationConstant.COL_CATEGORY_ENG_NAME);
							String image = jsonCategory
									.getString(ApplicationConstant.COL_CATEGORY_IMAGE);
							Category c = new Category();
							c.setCategoryId(id);
							c.setImageSrc(image);
							c.setName(name);
							c.setEngName(engName);
							// add bitmap to locate
							String urldisplay = ApplicationConstant.URL_IMAGES
									+ image;
							Bitmap mIcon11 = null;
							try {
								InputStream in = new java.net.URL(urldisplay)
										.openStream();
								mIcon11 = BitmapFactory.decodeStream(in);
							} catch (Exception e) {
								e.printStackTrace();
							}
							c.setBitmap(mIcon11);
							listCategory.add(c);
						}
						Log.d("--thoainguyen", "---list category:"
								+ listCategory.size());
						adapterMainCategory.notifyDataSetChanged();
						layoutLoading.setVisibility(View.GONE);
						// Log.d("answerasdasd", answer);
					} catch (JSONException e) {
						e.printStackTrace();
					}

				}
				break;

			case HttpPostThread.FAILURE:
				// do some error handling

				break;

			default:
				break;
			}
		}
	};;
}
